//
//  AppDelegate.m
//  KLCurrency
//
//  Created by apple on 2017/12/2.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "AppDelegate.h"

#import "KLCurrencyExchangeTableController.h"
#import "KLNavigationController.h"

#import "KLCurrencyEntity.h"
#import "KLDBHelper.h"
#import "KLPlistHelper.h"
#import "KLCurrencyHelper.h"
#import "KLCurrencyService.h"

#import "KLLocationHelper.h"


@interface AppDelegate ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;//定位服务

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //定位获取location,定位结束后开启数据库和主界面
    [self getCurrentLocation];
    return YES;
}

- (void)initDataAndRootViewControllerWithLocation:(NSString *)location{
    //加载所有本地数据
    [self initDBWithLocation:location];
    [self initPlist];
    //创建根控制器
    [self initRootViewController];
}

- (void)getCurrentLocation {
    [[KLLocationHelper sharedInstance] getCurrentLocation:^(CLLocation * _Nullable location, CLPlacemark * _Nullable placemark, NSString * _Nullable error) {
        if (placemark) {
            //转换地址为货币区域
            NSString *currencyArea = [KLCurrencyHelper currencyAreaWithPlacemark:placemark];
            [self initDataAndRootViewControllerWithLocation:currencyArea];
        } else {
            KLLog(@"%@",error);
            [self initDataAndRootViewControllerWithLocation:kDefaultLocalCurrencyNation];
        }
    }];
}

- (void)initRootViewController {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    KLCurrencyExchangeTableController *main = [[KLCurrencyExchangeTableController alloc] init];
    KLNavigationController *mainNav = [[KLNavigationController alloc] initWithRootViewController:main];
    self.window.rootViewController = mainNav;
    [self.window makeKeyAndVisible];
}

- (void)initDBWithLocation:(NSString *)location {
    NSString *dbPath = [KLDBHelper dbPath];
    
    BOOL dbExit = [[NSFileManager defaultManager] fileExistsAtPath:dbPath isDirectory:nil];
    
    if (!dbExit) {
        [KLDBHelper buildDataBase];
    }
    KLLog(@"dbPath: %@",dbPath);
    //第一次导入默认数据
    long long count = [KLCurrencyService getCountOfAllCurrencyEntities];
    if (count == 0) {
        [self writeDefualtDBDataWithLocation:location];
    } else {
        KLLog(@"已经有数据");
        //确认和更新定位数据
        [KLCurrencyService updateLocalCurrencyWithLocation:location];
    }
}

- (void) initPlist {
    NSString *plistPath = [KLPlistHelper plistFolder];
    BOOL fileExit = [[NSFileManager defaultManager] fileExistsAtPath:plistPath isDirectory:nil];
    if (!fileExit) {
        [KLPlistHelper buildPlistFile];

        [KLCurrencyService saveDefaultMainCurrencies];
        [KLCurrencyService saveDefaultExchangeRateDictionary];
    }
}

- (void)writeDefualtDBDataWithLocation:(NSString *)location{
    //如果本地缓存数据为空 那么数据清空
    NSArray<NSDictionary *> *dictArray = [KLCurrencyHelper allCurrencies];
    NSMutableArray<KLCurrencyEntity *> *modelArr = [NSMutableArray array];
    
    NSArray *mainArr = [KLCurrencyHelper defaultMainCurrencyAbbreviation];

    for (NSDictionary *dict in dictArray) {
        KLCurrencyEntity *item = [[KLCurrencyEntity alloc] initWithDictionary:dict];
        
        if ([item.nation isEqualToString:location]) {
            item.local = YES;
        }else {
            item.local = NO;
        }
        if ([mainArr containsObject:item.abbreviation]) {
            item.common = YES;
            item.main = YES;
        }else {
            item.common = NO;
            item.main = NO;
        }
        [modelArr addObject:item];
    }
    
    NSArray<KLCurrencyEntity *> *allModelArr = [modelArr mutableCopy];
    
    long long currencyCount = [KLCurrencyService importDefaultCurrencies:allModelArr];

    KLLog(@"写入默认数据成功-%lld",currencyCount);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
